package com.lizhivscaomei.cleanduplicatefiles.cmd.event;

import com.alibaba.fastjson.JSON;
import com.lizhivscaomei.cleanduplicatefiles.CleanDuplicateFilesApplication;
import org.apache.commons.io.FileUtils;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;

/**
 * @author lizhi
 */
@Component
public class FileEventListener implements ApplicationListener<FileEvent> {
    @Override
    public void onApplicationEvent(FileEvent fileEvent) {

        int total = fileEvent.getConfig().getMatchFiles().size();
        final int[] unfinished = {0};
        fileEvent.getConfig().getMatchFiles().forEach((file, aBoolean) -> {
            if (!aBoolean) {
                unfinished[0]++;
            }
        });
        System.out.println("(" + unfinished[0] + "/" + total + ")");
        if (unfinished[0] == 0) {
            File result = new File("result.json");
            try {
                fileEvent.getConfig().getResultsTemp().forEach((path, resultTemp) -> {
                    if (resultTemp.getAll().size() > 1) {
                        resultTemp.setSave(new String[]{(String) resultTemp.getAll().toArray()[0]});
                        HashSet<String> deleteTemp = (HashSet<String>) resultTemp.getAll().clone();
                        deleteTemp.remove(resultTemp.getSave()[0]);
                        resultTemp.setDelete(deleteTemp);
                        fileEvent.getConfig().getResults().add(resultTemp);
                    }
                });
                FileUtils.writeStringToFile(result, JSON.toJSONString(fileEvent.getConfig().getResults()),"UTF-8");
                System.out.println("scan result will write to file:"+result.getAbsolutePath());
                System.out.println("run cmd clean,delete all duplicate files");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
